package com.shop.front.shiro;

import com.shop.domain.user.User;
import com.shop.web.shiro.token.BaseUsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

public class UserShiroUtil {

    // 固定盐值
    public static final String ENCRYPT_FIXED_SALT = "bjwhqw91as828qgr718da9234H12hr99";
    // 加密方式
    public static final String ENCRYPT_ALGORITHM = "MD5";
    // 散列的次数，比如散列两次，相当于 md5(md5(""));
    public static final int ENCRYPT_ITERATIONS = 1;

    public static Subject login(String name, String pwd, long timeout) {
        Subject subject = UserShiroUtil.getSubject();
        UsernamePasswordToken adminnamePasswordToken = new BaseUsernamePasswordToken(name, pwd);
        subject.login(adminnamePasswordToken);
        subject.getSession().setTimeout(timeout * 1000L);
        return subject;
    }

    public static Subject login(String name, long timeout) {
        Subject subject = UserShiroUtil.getSubject();
        UsernamePasswordToken adminnamePasswordToken = new BaseUsernamePasswordToken(name);
        subject.login(adminnamePasswordToken);
        subject.getSession().setTimeout(timeout * 1000L);
        return subject;
    }

    public static boolean isLogin() {
        if(null == SecurityUtils.getSubject()) {
            return false;
        }
        if(null == SecurityUtils.getSubject().getPrincipal()) {
            return false;
        }
        return null != SecurityUtils.getSubject().getPrincipal();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static User getUser() {
        return (User) getSubject().getPrincipal();
    }

    public static String getAccessToken() {
        return getSubject().getSession().getId().toString();
    }

    public static ByteSource byteSource(String str) {
        return ByteSource.Util.bytes(str);
    }

    /**
     * 加密密码
     * @param pwd
     * @return
     */
    public static String encryptPwd(String pwd) {
        return new SimpleHash(ENCRYPT_ALGORITHM, pwd, UserShiroUtil.byteSource(ENCRYPT_FIXED_SALT), ENCRYPT_ITERATIONS).toString();
    }
}
